package main

import (
	"bytes"
	amqp "github.com/rabbitmq/amqp091-go"
	"log"
	"time"
	"zhongxc.cc/go-common/errs"
	"zhongxc.cc/go-common/mq"
)

func Worker() {
	// 1. 建立链接
	conn := mq.NewRabbitMqConnection()
	defer func(conn *amqp.Connection) {
		_ = conn.Close()
	}(conn)

	// 2. 获取channel
	channel, err := conn.Channel()
	errs.FailOnError(err, "Failed to open a channel")
	defer func(channel *amqp.Channel) {
		_ = channel.Close()
	}(channel)

	err = channel.Qos(1, 0, false)
	errs.FailOnError(err, "ch.Qos() failed, err:")

	queue, err := channel.QueueDeclare(
		"task_queue",
		true, // 声明为持久队列
		false,
		false,
		false,
		nil,
	)
	errs.FailOnError(err, "Failed to declare a queue")

	consume, err := channel.Consume(
		queue.Name,
		"",
		false, // false：关闭自动消息确认
		false,
		false,
		false,
		nil,
	)

	// 开启循环不断地消费消息
	forever := make(chan bool)
	go func() {
		for d := range consume {
			log.Printf("Received a message: %s\n", d.Body)
			dotCount := bytes.Count(d.Body, []byte("."))
			t := time.Duration(dotCount)
			time.Sleep(t * time.Second) // 模拟耗时任务
			log.Printf("Done\n")
			err := d.Ack(false) // 手动传递消息确认
			if err != nil {
				log.Printf("消息确认失败")
				return
			}
		}
	}()
	log.Printf("[*] Waiting for messages. To exit press CTRL+C")
	<-forever
}

func main() {
	Worker()
}
